<?php

require_once(dirname(__FILE__).'/Constants.php');
require_once(dirname(__FILE__).'/Config.php');
require_once(dirname(__FILE__).'/DB.php');
require_once(dirname(__FILE__).'/Util.php');

class Statistics {
    public $count_date;
    public $table_name;
    public $insert = 0;
    public $update = 0;
    public $delete = 0;
    
    public function Statistics ($table_name = 'schedules', $count_date = '') {
        if (!$count_date || !is_date($count_date) || !$table_name) return FALSE;
        $this->count_date = $count_date;
        $this->table_name = $table_name;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            SELECT
                action,
                count
            FROM
                statistics
            WHERE
                count_date = '%s' AND
                table_name = '%s'",
            mysql_real_escape_string($count_date),
            mysql_real_escape_string($table_name)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        while ($row = mysql_fetch_assoc($result)) {
            $action = $row['action'];
            $this->$action = $row['count'];
        }
        return;
    }
    
    public function increment ($action) {
        if (!$this || !is_date($this->count_date) || !$this->table_name) return FALSE;
        
        $this->$action++;
        
        $dbh = DB::load_dbh();
        $result = mysql_query(sprintf("
            REPLACE INTO
                statistics
            SET
                count_date = '%s',
                table_name = '%s',
                action     = '%s',
                count      = '%d'",
            mysql_real_escape_string($this->count_date),
            mysql_real_escape_string($this->table_name),
            mysql_real_escape_string($action),
            mysql_real_escape_string($this->$action)
        ));
        if (!$result) {
            trigger_error(mysql_error, E_USER_WARNING);
            return FALSE;
        }
        return TRUE;
    }
}
